package com.hnhcyy.goods.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnhcyy.b2b.common.exception.ExceptionCast;
import com.hnhcyy.goods.mapper.*;
import com.hnhcyy.goods.pojo.*;
import com.hnhcyy.goods.service.GoodsAdminService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 后台提供服务impl
 *
 * @author gesh
 */
@Service
public class GoodsAdminServiceImpl implements GoodsAdminService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsExtendMapper goodsExtendMapper;
    @Autowired
    SpitemRelationMapper spitemRelationMapper;
    @Autowired
    SpkfklackMapper spkfklackMapper;
    @Autowired
    ShoppingcartMapper shoppingcartMapper;

    public static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 获取所有商品列表
     */
    @Override
    public String listAllGoods(GoodsAdminQueryParam queryParam) {

        System.out.println("-=-=-=-" + queryParam.toString());

        List<Goods> list = goodsMapper.listAllGoods(queryParam);

        //转化为json字符串返回，因为admin端调用用的是原生feign，直接返回List和Mapper会提示解码错误

        String result = "";
        try {
            result = MAPPER.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("---->" + result);
        return result;
    }

    /**
     * 更新商品信息
     */
    @Transactional
    @Override
    public String updateGoods(Goods goods) {

        //更新主表
        int goodsUpdateResult = goodsMapper.updateItem(goods);

        if (0 == goodsUpdateResult) {
            //主表更新失败
            return goodsUpdateResult + "";
        }

        //获取spid并设置进goodsExtend中
        String spid = goods.getSpid();
        GoodsExtend newExtend = goods.getGoodsExtend();

        //为空时,不更新扩展表
        if (null == newExtend) {
            return goodsUpdateResult + "";
        }

        String result = "";
        newExtend.setSpid(spid);
        //更新扩展表
        result = updateGoodsExtend(newExtend);
        System.out.println("----->参数" + goods.toString());

        return result;
    }

    /**
     * 更新商品图片信息
     */
    @Override
    public String updateGoodsPicture(Goods goods) {

        String spid = goods.getSpid();
        //获取原Fver
        String fver = goodsMapper.selectFverBySpid(spid);
        System.out.println("fver---" + fver);
        if (StringUtils.isEmpty(fver)) {
            fver = "0";
        }
        int fverInt = Integer.parseInt(fver);
        goods.setFver(fverInt + 1);
        //更新主表
        int goodsUpdateResult = goodsMapper.updateItem(goods);


        return goodsUpdateResult + "";
    }

    @Override
    public boolean updateOrSaveGoods(Goods goods) {
        // 1、查询商品是否已经存在
        int count = goodsMapper.selectCountById(goods);
        // 新增或者更新影响行数
        int affect = 0;
        if (count == 0) {
            // 新增商品
            affect = goodsMapper.insertItem(goods);
        } else {
            // 更新商品
            affect = goodsMapper.updateItem(goods);
        }
        return affect == 1;
    }

    /**
     * 更新扩展表信息
     */
    @Override
    public String updateGoodsExtend(GoodsExtend goodsExtend) {

        // 获取参数
        Integer sjid = goodsExtend.getSjid();
        String spid = goodsExtend.getSpid();
        // 首先查询是否已经存在goods_extend记录，不存在则新增，存在则更新
        GoodsExtend oldItem = goodsExtendMapper.selectItemBySjidAndSpid(sjid, spid);

        if (null == oldItem) {
            // 若没有记录,则新增记录
            int result = goodsExtendMapper.insertItem(goodsExtend);
            return result + "";
        }

        //有记录，则修改记录
        int updateResult = goodsExtendMapper.updateItem(goodsExtend);

        //如果是下架商品，则同时删除关联商品记录
        Boolean oldIsvisible = oldItem.getIsvisible();
        Boolean newIsvisible = goodsExtend.getIsvisible();
        if (null != newIsvisible) {
            if (oldIsvisible != newIsvisible && oldIsvisible) {

                //删除关联商品记录
                SpitemRelation spitemRelation = new SpitemRelation();
                spitemRelation.setGlspid(spid);
                spitemRelation.setSjid(sjid);
                spitemRelationMapper.deleteByGlspidAndSjid(spitemRelation);

                //删除缺货记录
                Spkfklack spkfklack = new Spkfklack();
                spkfklack.setSpid(spid);
                spkfklack.setSjid(sjid);
                spkfklackMapper.deleteBySpidAndSjid(spkfklack);

                //删除购物车记录
                Shoppingcart shoppingcart = new Shoppingcart();
                shoppingcart.setSpid(spid);
                shoppingcart.setSjid(sjid);
                shoppingcartMapper.deleteBySpidAndSjid(shoppingcart);
            }
        }

        return updateResult + "";

    }

    @Override
    public List<String> getSpidListOnSell() {
        return goodsExtendMapper.selectSpidListOnSell();
    }

    @Override
    @Transactional
    public int updateGoodsList(List<Goods> goodsList) {
        // 更新购物车商品的价格 （并行执行流）
        goodsList.parallelStream().forEach(goods -> {
            Shoppingcart shoppingcart = new Shoppingcart();
            shoppingcart.setSpid(goods.getSpid());
            shoppingcart.setFprice(goods.getPrice());
            shoppingcartMapper.updateItem(shoppingcart);
        });
        int affectRows = goodsMapper.updateList(goodsList);
        if (affectRows == 0) {
            // 更新失败，抛出异常，回滚
            ExceptionCast.cast(GoodsResultEnum.GOODS_UPDATE_FAIL);
        }
        return affectRows;
    }

    /**
     * 修改商品价格
     */
    @Transactional
    @Override
    public String updateGoodsFprice(Goods goods) {

        int goodsUpdateResult = goodsMapper.updateItem(goods);//修改调用佘通用方法商品价格
        if (goodsUpdateResult == 0) {
            //商品表更新失败
            System.out.println("--GoodsPrice价格失败+++---" + goodsUpdateResult);
            return null;
        }
        System.out.println("--GoodsPrice价格成功+++---" + goodsUpdateResult);
        //判断购物车是否有数量
        int count = shoppingcartMapper.selectShoppingcartById(goods.getSpid());
        if(count == 0){
            // 购物车没有该商品，直接返回结果
            return goodsUpdateResult + "";
        }
        // 执行修改购物车价格
        Shoppingcart shoppingcart = new Shoppingcart();//购物车
        shoppingcart.setFprice(goods.getPrice());//单价
        shoppingcart.setSpid(goods.getSpid());//购物车商品
        int ok = shoppingcartMapper.updateItem(shoppingcart);
        if (ok == 0) {
            // 更新失败，抛出异常，回滚
            ExceptionCast.cast(GoodsResultEnum.GOODS_UPDATE_FAIL);
        }
        return goodsUpdateResult + "";

    }


}
